<template>
    <x-popup v-model="showPopup" top="30vh" :auto-hide-tab-bar="props.autoHideTabBar">
        <view class="flex flex-center px-4">
            <view class="w-100px">
            </view>
            <view class="flex-1 h8 font-weight-600 p-10 text-center">{{ fastTitle }}</view>
            <view class="w-100px"></view>
        </view>
        <!-- #ifdef H5 -->
        <view class="flex-1 flex overflow-hidden flex-column flex-x-center px-10">
            <view class="bg-grey rounded-round flex flex-center px-4">
                <view class="w-30px">
                    <uni-icons type="phone" size="30" color="var(--xl-dark-light-5)"></uni-icons>
                </view>
                <input ref="mobileRef" v-model="mobile" type="tel" class="flex-1 h4 font-weight-600 mx-4 py-4 text-primary"
                    placeholder="手机号" placeholder-class="h8" maxlength="13" @input="formatMobile">
                <view class="w-30px">
                    <uni-icons v-if="mobile" type="close" size="30" color="var(--xl-dark-light-5)"
                        @tap="mobile = '', mobileRef.focus()"></uni-icons>
                </view>
            </view>
            <view class="bg-grey rounded-round flex flex-center px-4 mt-6" v-if="WEBCONFIG?.imgcode">
                <view class="w-30px">
                    <uni-icons type="image" size="30" color="var(--xl-dark-light-5)"></uni-icons>
                </view>
                <input ref="mobileRef" v-model="form.imgcode" type="text"
                    class="flex-1 h4 font-weight-600 mx-4 py-4 text-primary" placeholder="图形验证码" placeholder-class="h8"
                    maxlength="6">
                <image :src="captchaUrl" class="captcha-image" mode="aspectFit" @tap="getCaptchaUrl" />
            </view>
            <view class="bg-grey rounded-round flex flex-center px-4 mt-6">
                <view class="w-30px">
                    <uni-icons type="email" size="30" color="var(--xl-dark-light-5)"></uni-icons>
                </view>
                <input ref="mobileRef" v-model="form.vcode" type="tel"
                    class="flex-1 h4 font-weight-600 mx-4 py-4 text-primary" placeholder="验证码" placeholder-class="h8"
                    maxlength="6">
                <view class="h10 font-weight-600" @tap="getVcode"
                    :class="vcodeBtn.disabled ? 'text-dark-light-5' : 'text-primary'">{{ vcodeBtn.text }}</view>
            </view>
        </view>
        <!-- #endif -->
        <!-- #ifdef MP-WEIXIN -->
        <view class="flex-1 flex overflow-hidden flex-column flex-x-center px-10">
            <view class="flex flex-center px-4 mb-10 flex-column">
                <button open-type="chooseAvatar" @chooseavatar="chooseavatar" class="avatar-btn bg-grey">
                    <image v-if="form.avatar" :src="form.avatar" class="avatar"/>
                    <uni-icons type="person-filled" size="30" color="var(--xl-dark-light-5)" v-else/>
                </button>
                <view class="h8 text-placeholder pt-2 font-weight-600">头像</view>
            </view>
            <view class="bg-grey rounded-round flex flex-center px-4">
                <view class="w-30px">
                    <uni-icons type="person" size="30" color="var(--xl-dark-light-5)"></uni-icons>
                </view>
                <input type="nickname" v-model="form.nickname" class="flex-1 h4 font-weight-600 mx-4 py-4 text-primary"
                    placeholder="昵称" placeholder-class="h8">
            </view>
        </view>
        <!-- #endif -->
        <view class="pb-safe-area">
            <view class="py-10">
                <view class="flex flex-center">
                    <view class="bg-primary text-white rounded-round w-50 py-4 font-weight-600 text-center"
                        hover-class="bg-primary-dark-1" @tap="submit">登录/注册</view>
                </view>
                <view class="flex flex-center mt-4" @tap="form.agreement= !form.agreement">
					<uni-icons type="circle-filled" v-if="form.agreement" color="var(--xl-primary)"/>
					<uni-icons type="circle" v-else color="var(--xl-dark-light-5)"/>
                    <view class="h10 text-dark-light-5 pl-2">请阅读并同意</view>
                    <view class="h10 text-primary ml-2" @tap.stop="openAgreement">《用户协议》</view>
                </view>
            </view>
        </view>
    </x-popup>
</template>

<script lang="ts" setup>
import { onMounted, ref,defineProps } from "vue";
import { useUserStore, useWebConfigStore, useRefs } from "@/stores";
import { onShow } from "@dcloudio/uni-app";
import { $http, $message,$page,$system } from '@/utils';
const props = withDefaults(defineProps<{
	autoHideTabBar?: boolean,
}>(), {
});
const webConfigStore = useWebConfigStore();
const { WEBCONFIG } = useRefs(webConfigStore);
const { setUserInfo } = useUserStore();
const fastTitle = WEBCONFIG.value?.web_name || $system.name();
const showPopup = ref(false);
const mobileRef = ref();
const mobile = ref('');
const captchaUrl = ref($http.baseURL + 'Login/captcha');
const emit = defineEmits(['success']);
const formatMobile = () => {
    let phoneNumber = mobile.value.replace(/\D/g, '');
    form.value.mobile = phoneNumber;
    // 格式化手机号：188 8888 8888
    if (phoneNumber.length > 3 && phoneNumber.length < 8) {
        phoneNumber = phoneNumber.replace(/(\d{3})(\d{1,4})/, '$1 $2');
    } else if (phoneNumber.length >= 8) {
        phoneNumber = phoneNumber.replace(/(\d{3})(\d{1,4})(\d{1,4})/, '$1 $2 $3');
    }
    mobile.value = phoneNumber;
}
const form = ref<any>({
    mobile: '',
    imgcode: '',
    vcode: '',
    code:'',
    avatar: '',
    nickname: '',
    agreement: false
});
const show = (options: any) => {
    // #ifdef H5
    showPopup.value = true;
    form.value.agreement = true;
    // #endif
    
    // #ifdef MP-WEIXIN
    uni.showLoading({
        title: '登录中...',
        mask: true
    })
    wx.login({
        success:(res:any)=>{
            if (res.code) {
                form.value.code = res.code;
                $http.post('Login/wechatMPCode',{
                    data:{
                        code:res.code
                    }
                }).then((res:any)=>{
                    if (res.code === $http.ResponseCode.SUCCESS) {
                        $message.success('登录成功');
                        setUserInfo(res.data).then(() => {
                            restForm();
                            showPopup.value = false;
                            emit('success');
                        })
                    } else if(res.code === $http.ResponseCode.NEED_LOGIN) {
                        uni.showModal({
                            title: '提示',
                            content: '登录失败，' + res.msg,
                            showCancel: false,
                            success: () => {
                                showPopup.value = false;
                            }
                        })
                    }else{
                        showPopup.value = true;
                    }
                }).finally(() => {
                    uni.hideLoading();
                })
            } else {
                uni.hideLoading();
                uni.showModal({
                    title: '提示',
                    content: '登录失败，' + res.errMsg,
                    showCancel: false,
                    success: () => {
                        showPopup.value = false;
                    }
                })
            }
        },
        fail:(err:any)=>{
            uni.hideLoading();
            uni.showModal({
                title: '提示',
                content: '微信登录失败，'+err.errMsg,
                showCancel: false,
                success: () => {
                    showPopup.value = false;
                }
            })
        }
    })
    // #endif
}
const restForm = () => {
    mobile.value = '';
    form.value.mobile = '';
    form.value.vcode = '';
}
const submit = () => {
    uni.showLoading({
        title: '登录中...',
        mask: true
    })
    // #ifdef H5
    $http.post('Login/vcode', {
        data: form.value
    }).then((res: any) => {
        if (res.code === $http.ResponseCode.SUCCESS) {
            $message.success('登录成功');
            setUserInfo(res.data).then(() => {
                restForm();
                showPopup.value = false;
                emit('success');
            })
        } else {
            $message.error(res.msg);
        }
    }).finally(() => {
        uni.hideLoading();
    })
    // #endif
    // #ifdef MP-WEIXIN
    if(!form.value.agreement){
        $message.error('请先阅读并同意用户协议');
        return;
    }
    $http.post('Login/wechatMP', {
        data: form.value
    }).then((res: any) => {
        if (res.code === $http.ResponseCode.SUCCESS) {
            $message.success('登录成功');
            setUserInfo(res.data).then(() => {
                restForm();
                showPopup.value = false;
                emit('success');
            })
        } else {
            $message.error(res.msg);
        }
    }).finally(() => {
        uni.hideLoading();
    })
    // #endif
}
const vcodeBtn = ref({
    text: '获取验证码',
    disabled: false
})
const getVcode = () => {
    if (vcodeBtn.value.disabled) { return; }
    $http.post('Login/getVcode', {
        data: {
            mobile: form.value.mobile,
            imgcode: form.value.imgcode
        }
    }).then((res: any) => {
        if (res.code === $http.ResponseCode.SUCCESS) {
            vcodeBtn.value.disabled = true;
            let time = 60;
            const timer = setInterval(() => {
                vcodeBtn.value.text = `${time}s`;
                time--;
                if (time < 0) {
                    clearInterval(timer);
                    vcodeBtn.value.text = '获取验证码';
                    vcodeBtn.value.disabled = false;
                }
            }, 1000)
        } else {
            $message.error(res.msg);
        }
    });
}
const getCaptchaUrl = () => {
    captchaUrl.value = $http.baseURL + 'Login/captcha?' + Math.random();
}
const chooseavatar=(e:any)=>{
    uni.showLoading({
        title: '上传中...',
        mask: true
    })
    $http.upload('Upload/upload',{
        filePath:e.detail.avatarUrl,
        name:'file'
    }).then((res:any)=>{
        console.log(res);
        if (res.code === $http.ResponseCode.SUCCESS) {
            form.value.avatar = res.data.url;
        } else {
            $message.error(res.msg);
        }
    }).finally(() => {
        uni.hideLoading();
    })
}
const showAgreementModalState=ref(false);
const showAgreementModal=()=>{
    if(!showAgreementModalState.value){
        return;
    }
    showAgreementModalState.value=false;
    uni.showModal({
        title: '提示',
        content: '您是否同意用户协议？',
        cancelText: '不同意',
        confirmText: '同意',
        success: (res) => {
            if (res.confirm) {
                form.value.agreement = true;
            } else if (res.cancel) {
                form.value.agreement = false;
            }
        }
    })
}
const openAgreement=()=>{
    // #ifdef MP-WEIXIN
    showAgreementModalState.value=true;
    // #endif
    $page.open('/pages/article/content?alias=user_agreement');
}
onMounted(() => {
})
onShow(()=>{
    // #ifdef MP-WEIXIN
    showAgreementModal();
    // #endif
})
defineExpose({ show });
</script>

<style lang="scss" scoped>
.w-30px {
    width: 30px;
}

.w-100px {
    width: 100px;
}

.captcha-image {
    height: 60px;
    width: 100px;
}
.avatar-btn{
    width: 100px;
    height: 100px;
    border-radius: 50%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .avatar{
        width: 100px;
        height: 100px;
        border-radius: 50%;
    }
}
</style>